package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.behavior.IBehaviorFeign;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.threadlocal.ApThreadLocalUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Value("${file.oss.web-site}")
    private String webSiste; //oss域名


    @Autowired
    private IBehaviorFeign behaviorFeign;

    @Autowired
    private ApUserSearchService apUserSearchService;


    @Override
    public ResponseResult search(UserSearchDto dto) {
        //1.判断参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }



        if(dto.getFromIndex()==0){ //如果是首页第一次请求，就记录搜索关键词
            Integer userId = null;
            ApUser user = ApThreadLocalUtils.getUser();
            if(user!=null && user.getId()>0){
                userId = user.getId();
            }

            ApBehaviorEntry apBehaviorEntry = behaviorFeign.findByUserIdAndEquipmentId(userId, dto.getEquipmentId());
            Integer entryId = apBehaviorEntry.getId(); //行为实体ID

            //开启异步线程任务，执行搜索关键词保存
            apUserSearchService.insert(entryId,dto.getSearchWords());

        }


        //2.执行ES搜索

        //搜索请求对象
        SearchRequest searchRequest = new SearchRequest("app_info_article");


        //组合搜索对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").defaultOperator(Operator.OR)); //关键词匹配搜索
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime())); //发布时间小于最小时间


        //搜索源对象（添加搜索+对搜索结果的处理）
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(boolQueryBuilder); //添加搜索
        searchSourceBuilder.from(dto.getPageNum()).size(dto.getPageSize()) ; //搜索分页
        searchSourceBuilder.sort("publishTime", SortOrder.DESC); //按照发布时间倒排

        searchRequest.source(searchSourceBuilder);


        List<Map> aritcleMapList = new ArrayList<>();
        try {
            //执行搜索
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            //获取搜索命中
            SearchHit[] searchHits = searchResponse.getHits().getHits();


            if(searchHits!=null && searchHits.length>0){
                for (SearchHit searchHit : searchHits) {
                    String articleJSON = searchHit.getSourceAsString();
                    Map articleMap = JSON.parseObject(articleJSON, Map.class);//将搜索命中的文章JSON字符串转为MAP文章对象
                    aritcleMapList.add(articleMap);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        //3.封装响应结果
        ResponseResult responseResult = ResponseResult.okResult(aritcleMapList);
        responseResult.setHost(webSiste);

        //4.响应
        return responseResult;
    }
}
